package com.xhs.config;

import com.mybatisflex.core.audit.AuditMessage;
import com.mybatisflex.core.audit.MessageCollector;
import com.xhs.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @desc: mybatis-Flex 收集的SQL输出到控制台
 * @projectName: mybatis-flex-demo
 * @author: xhs
 * @date: 2023-09-13  18:12
 * @version: JDK 1.8
 */
@Slf4j
@Component
public class ConsoleMessageCollector implements MessageCollector {
    @Value("${spring.application.name}")
    private String serviceName;
    @Override
    public void collect(AuditMessage message) {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        String ipAddr = addr.getHostAddress();
        message.setUrl(ipAddr);
        message.setPlatform(serviceName);
        StringBuilder buffer = new StringBuilder();
        buffer.append(Constants.LINE);
        buffer.append(Constants.LINE_HEADER).append(" SQL START ").append(Constants.LINE_HEADER).append(Constants.LINE);
        buffer.append(Constants.IN_HEADER).append("AuditMessage:").append(message).append(Constants.LINE);
        buffer.append(Constants.IN_HEADER).append("SQL:").append(message.getFullSql()).append(Constants.LINE);
        buffer.append(Constants.IN_HEADER).append("SQL耗时:").append(message.getElapsedTime()).append("毫秒").append(Constants.LINE);
        buffer.append(Constants.LINE_HEADER).append(" SQL END   ").append(Constants.LINE_HEADER).append(Constants.LINE);
        log.info(buffer.toString());
    }
}
